package Sync;

import Sync.Tool.SyncTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.SocketException;

public class SyncSendThread extends Thread{
    private static final Logger log = LoggerFactory.getLogger(SyncReceiveThread.class);
    private final SharedSocket sharedSocket;
    private final InteractiveLogic interactiveLogic;


    public SyncSendThread(SharedSocket sharedSocket, InteractiveLogic interactiveLogic) {
        this.sharedSocket= sharedSocket;
        this.sharedSocket.increment();
        this.interactiveLogic = interactiveLogic;

    }
    @Override
    public void run(){
        try {
           while (true){
               //阻塞发送线程
               sharedSocket.waitForSend();
               //创建数据输出流
               DataOutputStream dos = new DataOutputStream(sharedSocket.getOutputStream());


               //将InteractiveLogic对象转为JSON字符串,发送给手机端
               dos.writeUTF(SyncTool.toJson(interactiveLogic));
               //获取电脑端要发给手机端的同步文件内容
               if (interactiveLogic.getFileContentSync_PC_Count()>0){
                   int syncSum=interactiveLogic.getFileContentSync_PC_Count();
                   for (int i=1; i <=syncSum; i++) {
                       File file = interactiveLogic.getFileContentSync_PC().get(i-1);
                       sendFile(dos,file);

                   }
               }
               dos.flush();
               //电脑端要发给手机端的新增文件
               if(interactiveLogic.getFileAdditionSync_PC_Count()>0){
                   int syncSum=interactiveLogic.getFileAdditionSync_PC_Count();
                   for (int i=1; i <=syncSum; i++) {
                       File file = interactiveLogic.getFileAdditionSync_PC().get(i-1);
                       sendFile(dos,file);
                   }

               }
               dos.flush();
              if (sharedSocket.isShouldStopSending()) break;
           }
            log.info("发送线程正常结束");
            sharedSocket.decrement();
           log.info("发送线程正常结束");

        } catch (EOFException ignored) {
            log.debug("接收线程正常结束：客户端已关闭连接");
        } catch (SocketException e) {
            if (e.getMessage().contains("Socket closed")) {
                log.debug("接收线程正常结束：套接字已关闭");
            } else {
                log.error("网络传输异常：{}", e.getMessage(), e);
            }
        } catch (IOException e) {
            log.error("网络传输异常：{}", e.getMessage(), e);
        } catch (Exception e) {
            log.error("处理异常：{}", e.getMessage(), e);
        }


    }
    /**
     * 发送单个文件到输出流
     * @param dos 数据输出流
     * @param file 要发送的文件
     * @throws IOException 当IO操作出现异常时抛出
     */
    private void sendFile(DataOutputStream dos, File file) throws IOException {
        dos.writeUTF(file.getName());
        dos.writeLong(file.length());
        dos.flush();
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytesRead);
        }
        fis.close();
    }


}
